Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

323
Visualizações
how to return values from JS .then function [using arrow function]

Unsure how to access the values date and prices else where in the script

fetch("fileName")
.then(response => response.json())
.then(data => {
    var date  = data.JSONdata[data.JSONdata.length - 1].date
    var prices = data.JSONdata[data.JSONdata.length - 1].prices
})
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can simply rewrite your code to use async/await:

const response = await fetch("fileName");
const data = await response.json();
const date  = data.JSONdata[data.JSONdata.length - 1].date;
const prices = data.JSONdata[data.JSONdata.length - 1].prices;

EDIT: To use this asynchronous code, you have to define the function in which you use this code as async:

async function yourFunction() {
    // your async code from above
}

// await async function where it's called
const functionResult = await yourFunction();

You have to make every function in your callstack async up to the level where you no longer care about the response. So the function which calls "yourFunction()" has to be async aswell. And so on.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use await to get the Promise result. Please refer MDN docs

In the given example date and prices are hard-coded which will be fetched via API calls in real-scenario

const date = Date.now();
const prices = [1000, 2000];
const resolvedProm = Promise.resolve({date, prices});

let thenProm = resolvedProm.then(({date, prices}) => {
    return {date, prices};
});

let res = await thenProm;
console.log(res); 
// {date: 1641136463085, prices: Array(2)}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda